<template>
	<view class="user-register">
		<view class="login-header flexC">
			<image src="../../static/images/swiper/2.jpg" mode=""></image>
			<view class="hospital">{{hospitalInfo.name}}</view>
			<view>{{'WELCOME TO VISIT OUR HOSPITAL'}}</view>
		</view>
		<view class="user-register-mian">

			<view class="btn">
				<button type="default" @click="onRegister">{{editInfo?'保存':'注册'}}</button>
				<button @click="backHome">回到首页</button>
			</view>
		</view>
		<!-- 一键上传省份证信息组件 -->
		<input type="file" value="" />
		<Load :load="load"></Load>
	</view>
</template>

<script>
	import {
		mapGetters,
		mapActions
	} from 'vuex'
	import {
		getRegisterList,
		poRegister,
		puRegister,
		getCode,
		poIdCardImgInfo
	} from '@/api/login.js'
	import {
		getDict
	} from '@/api/system.js'
	import Load from '@/components/Load/index.vue'
	import {
		address
	} from '@/utils/listAddress.js'
	import {
		deepCopy
	} from '../../utils/assist.js'
	import {
		themeColor
	} from '@/static/js/theme.js'
	import {
		phoneReg,
		cardReg,
		idCard
	} from '@/common/js/reg.js'
	import {
		getValue
	} from '@/common/js/common.js'
	// import idCard from 'idcard'
	export default {
		components: {
			Load
		},
		dicts: ['jobCode', 'sex', 'maritalStatus'],
		data() {
			return {
				themeColor,
				address,
				showSelect: false,
				showDate: false,
				showArea: false,
				codeText: true,
				defaultArea: [11, 1101, 110106],
				defaultDate: '',
				key: 'sex',
				registerList: [],
				formInfo: {},
				load: false,
				wecChatCode: undefined,
				editInfo: null, //修改时携带信息
				baseInfo: null, //登录时未注册携带的信息
			}
		},
		computed: {
			...mapGetters(['hospitalInfo', 'userId', 'systemParams', 'healthCardType', 'hostApi']),
			action() {
				if (this.hostApi) {
					return this.hostApi + '/api/healthCard/scanIdentityCard'
				} else {
					return 'http://ss'
				}
			}
		},
		onLoad(options) {
			if (options.editInfo) {
				this.editInfo = JSON.parse(options.editInfo)
			}
			if (options.baseInfo) {
				this.baseInfo = JSON.parse(options.baseInfo)
			}
		},
		created() {
			this.getConfig()
		},
		methods: {
			...mapActions(['getBindInfo']),
			// 获取患者注册项
			getConfig() {
				let that = this;
				this.getBaseConfig()
				this.load = true;
				getRegisterList().then(data => {
					this.load = false;
					if (this.editInfo) {
						data.forEach(item => {
							if (item.name === 'cardType') {
								if (this.editInfo.cardTypeName) {
									this.formInfo[item.name] = [{
										label: this.editInfo.cardTypeName,
										value: this.editInfo.cardType
									}]
									item.disabled = true
								} else {
									this.formInfo[item.name] = ''
								}
							} else if (item.name === 'areaCode') {
								if (this.editInfo.defaultAddress) {
									this.formInfo[item.name] = JSON.parse(this.editInfo.defaultAddress)
								} else {
									if (this.hospitalInfo.defaultAddress) {
										this.formInfo[item.name] = JSON.parse(this.hospitalInfo
											.defaultAddress)
									} else {
										this.formInfo[item.name] = ''
									}
								}
							} else if (item.name === 'jobCode') {
								if (this.editInfo.jobName) {
									this.formInfo[item.name] = [{
										label: this.editInfo.jobName,
										value: this.editInfo.jobCode
									}]
								} else {
									this.formInfo[item.name] = ''
								}
							} else if (item.name === 'maritalStatus' || item.name === 'sex') {
								if (item.name === 'maritalStatus' && this.editInfo.maritalStatus) {
									this.formInfo[item.name] = [{
										label: this.editInfo.maritalStatus,
										value: this.editInfo.maritalStatusCode
									}]
								} else {
									if (item.name === 'sex' && this.editInfo.sex) {
										this.formInfo[item.name] = [{
											label: this.editInfo.sex,
											value: this.editInfo.sexCode
										}]
									} else {
										this.formInfo[item.name] = ''
									}
								}
							} else if (item.name === 'birth') {
								if (this.editInfo.birth) {
									this.formInfo[item.name] = [{
										label: this.editInfo.birth,
									}]
									if ((this.formInfo.cardType === '01' || this.formInfo.cardType ===
											'02') && this.editInfo.idCard) {
										item.disabled = true
									} else {
										this.defaultDate = this.editInfo.birth
									}
								} else {
									this.formInfo[item.name] = ''
								}
							} else if (item.name === 'rqfl') {
								if (this.editInfo.rqfl) {
									this.formInfo[item.name] = [{
										label: this.editInfo.rqflName,
										value: this.editInfo.rqfl,
									}]
									this.defaultDate = this.editInfo.birth
								} else {
									this.formInfo[item.name] = ''
								}
							} else if (item.name === 'cardNo') {
								if (this.formInfo.cardType === '01' || this.formInfo.cardType === '02') {
									this.formInfo[item.name] = this.editInfo.idCard || ''
								} else {
									this.formInfo[item.name] = this.editInfo.cardNo || ''
								}
								if (this.formInfo[item.name]) {
									item.disabled = true
								}
							} else {
								this.formInfo[item.name] = this.editInfo[item.name] || ''
							}
						})
					} else {
						data.forEach(item => {
							if (item.name === 'areaCode' && this.hospitalInfo.defaultAddress) {
								this.formInfo[item.name] = this.hospitalInfo.defaultAddress ? JSON.parse(
									this.hospitalInfo.defaultAddress) : ''
							} else {
								if ((item.name === 'cardNo' || item.name === 'name' || item.name ===
										'phoneNumber') && this.baseInfo) {
									this.formInfo[item.name] = this.baseInfo[item.name]
								} else {
									if (item.name !== 'cardType') {
										this.formInfo[item.name] = '';
									}
								}
							}
						})
					}
					this.registerList = data || []
				}).catch(e => {
					this.load = false
				})
			},
			// 获取证件类型列表
			getBaseConfig() {
				getDict('cardType').then(data => {
					this.dict.cardType = data || []
					if (!this.editInfo) {
						this.formInfo.cardType = [data[0]]
					}
				}).catch(e => {
					this.dict.cardType = []
				})
			},
			// 短信验证码
			getCurCode() {
				if (!this.formInfo.phoneNumber) {
					this.$u.toast('请填写手机号码');
					return
				}
				if (this.codeText) {
					this.load = true;
					getCode({
						phoneno: this.formInfo.phoneNumber
					}).then(data => {
						this.load = false;
						this.codeText = false;
						this.$u.toast('已向短信平台请求短信发送服务，注意查收手机信息');
					}).catch(e => {
						this.load = false;
					})
				}
			},
			countDownEnd() {
				this.codeText = true;
			},
			handleOtherSelect(item) {
				if (!item.disabled) {
					this.handleItem(item.name, 'showSelect')
				}
			},
			handleItem(key, type) {
				this.key = key
				this[type] = true
			},
			handleItemMy() {
				let _this = this;
				my.datePicker({
					currentDate: _this.defaultDate,
					startDate: '1900-01-01',
					endDate: '2045-01-01',
					success: (res) => {
						_this.formInfo.birth = [{
							label: res.date
						}]
						_this.defaultDate = res.date
					},
				});
			},
			confirm(e) {
				if (this.key === 'birth') {
					this.formInfo.birth = [{
						label: `${e.year}-${e.month}-${e.day}`
					}]
				} else {
					this.formInfo[this.key] = e
				}
			},
			// 处理身份证号码失焦事件
			handleValue(val, type) {
				if (type === 'cardNo' && this.formInfo.cardType[0].value == 1) {
					const {
						cardNo
					} = this.formInfo;
					if (!idCard.test(cardNo)) {
						this.$u.toast('请填写正确的身份证号码')
						this.formInfo.birth = ''
						this.formInfo.sex = ''
						return
					}
					if (cardNo.length > 14) {
						let birthYear = cardNo.substring(6, 10);
						let birthMonth = cardNo.substring(10, 12);
						let birthDate = cardNo.substring(12, 14);
						this.formInfo.birth = [{
							label: `${birthYear}-${birthMonth}-${birthDate}`
						}]
						this.defaultDate = `${birthYear}-${birthMonth}-${birthDate}`
						if (cardNo.length == 18) {
							let sex = ''
							if (cardNo.substring(16, 17) % 2 == 1) {
								sex = this.dict.sex.filter(item => item.label === '男')
							} else {
								sex = this.dict.sex.filter(item => item.label === '女')
							}
							this.formInfo.sex = sex;
						} else if (cardNo.length == 15) {
							let sex = ''
							if (cardNo.substring(14, 15) % 2 == 1) {
								sex = this.dict.sex.filter(item => item.label === '男')
							} else {
								sex = this.dict.sex.filter(item => item.label === '女')
							}
							this.formInfo.sex = sex;
						}
					}
				}
			},
			onRegister() {
				let that = this;
				let arr = this.registerList,
					flag = false
				for (let i = 0, len = arr.length; i < len; i++) {
					let item = arr[i].name
					if (this.formInfo[item] === '' && arr[i].required) {
						this.$u.toast(`请补充完善${arr[i].label}信息`);
						flag = true
						break;
					}
				}
				if (flag) {
					return
				}
				if (this.formInfo.cardType == undefined || !this.formInfo.cardType[0]) {
					this.formInfo = deepCopy(this.baseInfo);
					// this.formInfo  = this.baseInfo;
				}
				if (this.formInfo) {
					if (!phoneReg.test(this.formInfo.phoneNumber)) {
						this.$u.toast('请填写正确的手机号码');
						return
					}
					if (this.formInfo.cardType != undefined && this.formInfo.cardType[0].value == 1) {
						if (!idCard.test(this.formInfo.cardNo)) {
							this.$u.toast('请填写正确的身份证号');
							return
						}
					} else {
						if (!cardReg.test(this.formInfo.cardNo)) {
							this.$u.toast('请填写正确的证件号码');
							return
						}
					}
				}
				let params = {
					userId: this.userId,
					wecChatCode: this.wecChatCode
				}
				if (this.formInfo.cardType) {
					params.cardType = this.formInfo.cardType[0].value
				}
				if (this.formInfo.birth) {
					params.birth = this.formInfo.birth[0].label
				}
				if (params.cardType == "1" || params.cardType == "2") {
					const birth = this.formInfo.cardNo.substring(6, 14);
					const birthNew = params.birth.replace(RegExp("-", "g"), "");
					if (birth != birthNew) {
						this.$u.toast("身份证号和生日不符，请重新输入");
						return;
					}
				}
				if (this.formInfo.maritalStatus) {
					params.maritalStatus = this.formInfo.maritalStatus[0].value
				}
				if (this.formInfo.rqfl) {
					params.rqfl = this.formInfo.rqfl[0].value
				}
				if (this.formInfo.sex) {
					params.sex = this.formInfo.sex[0].value
				}
				if (this.formInfo.jobCode) {
					params.jobCode = this.formInfo.jobCode[0].value
					params.jobName = this.formInfo.jobCode[0].label
				}
				if (this.formInfo.areaCode) {
					params.sname = this.formInfo.areaCode[0].label
					params.sid = this.formInfo.areaCode[0].value
					params.djsName = this.formInfo.areaCode[1].label
					params.djsid = this.formInfo.areaCode[1].value
					params.xname = this.formInfo.areaCode[2].label
					params.xid = this.formInfo.areaCode[2].value
				}
				for (let key in this.formInfo) {
					if (Object.prototype.toString.call(this.formInfo[key]) !== '[object Array]') {
						params[key] = this.formInfo[key]
					}
				}
				this.load = true;
				if (this.editInfo) {
					params.patId = this.editInfo.patId
					puRegister(params).then(data => {
						this.getBindInfo(this.userId)
						let redirectPageUrl = uni.getStorageSync("editPageTo")
						if (!redirectPageUrl || 0 === redirectPageUrl.length) {
							uni.navigateBack();
						} else {
							uni.removeStorageSync("editPageTo")
							uni.navigateTo({
								url: redirectPageUrl
							})
						}
						this.load = false
					}).catch(() => {
						this.load = false
					})
				} else {
					poRegister(params).then(data => {
						this.getBindInfo(this.userId)
						let redirectPageUrl = uni.getStorageSync("redirect_page")
						if (!redirectPageUrl || 0 === redirectPageUrl.length) {
							uni.navigateBack();
						} else {
							uni.redirectTo({
								url: redirectPageUrl
							})
						}
						this.load = false
					}).catch(() => {
						this.load = false
					})
				}
			},
			backHome() {
				uni.reLaunch({
					url: '/pages/Index'
				})
			},
			// 扫描身份证
			onScanId() {
				this.load = true
				const this_ = this
				uni.chooseImage({
					count: 1,
					sizeType: "original",
					success: function(res) {
						let info = {
							imageData: res.tempFilePaths[0]
						}
						poIdCardImgInfo(info).then(data => {
							this_.load = false

						}).catch(e => {
							this_.load = false
						})
					},
					fail: function(err) {
						this_.load = false
						uni.showToast({
							title: "上传失败",
							icon: "none",
							duration: 2000
						})
					}
				})
			}
		}
	}
</script>

<style lang="scss" scoped>
	.user-register {
		min-height: calc(100vh);
		background-color: $uni-bg-color;
		color: $text-color;

		.login-header {
			height: 360rpx;
			color: $text-color-fff;
			padding-top: 36rpx;
			background-image: url(../../static/images/bg-header/login_header.png);
			background-repeat: no-repeat;
			background-size: cover;
			align-items: center;

			>image {
				height: 190rpx;
				width: 190rpx;
				border-radius: 10rpx;
				margin-bottom: 20rpx;
			}

			>view {
				font-size: 22rpx;
			}

			>.hospital {
				font-size: 40rpx;
				font-weight: bold;
				margin-bottom: 10rpx;
			}
		}

		.user-register-mian {
			padding: 30rpx 0;

			.form-main {
				padding: 10rpx 40rpx;

				.form-item-select {
					display: flex;
					flex-direction: row;
					align-items: center;
					padding: 10rpx 0;

					>label {
						display: inline-block;
						width: 150rpx;
						text-align: right;
					}

					>.form-item-select-right {
						flex: 1;
						display: flex;
						flex-direction: row;
						align-items: center;
						border: 1px solid $border-color;
						box-shadow: 9rpx 9rpx 9rpx rgba($color: #000000, $alpha: .06);
						border-radius: 30rpx;
						height: 70rpx;
						padding: 10rpx 16rpx;

						>view {
							width: 30rpx;
						}

						>text {
							flex: 1;
							font-size: 28rpx;
							padding: 20rpx;
						}

						>.form-item-right-input {
							flex: 1;
						}

						>.form-item-right-code {
							width: 160rpx;
							color: $theme-color;
						}

						.flexR {
							width: 200rpx;
							color: $theme-color;
						}
					}
				}
			}

			.btn {
				padding: 0 30rpx;

				button {
					margin-top: 20rpx;
					line-height: 90rpx;
					height: 90rpx;
					border: 1px solid $theme-color-light;
					border-radius: 12rpx;
					color: $theme-color-light;
				}

				button:first-child {
					border: none;
					background-color: $theme-color-light;
					color: $text-color-fff;
					margin-top: 40rpx;
				}
			}
		}
	}
</style>
<style lang="scss">
	.form-item-select-right {
		.u-input__input {
			height: 50rpx !important;
			min-height: 50rpx !important;
			padding-bottom: 0;
			padding-top: 0;
		}
	}

	.user-register-mian .u-form {
		padding: 10rpx 40rpx;

		.u-form-item--left__content__label {
			justify-content: flex-end !important;
		}

		.u-form-item {
			padding: 10rpx 0;
		}

		.u-form-item--left {
			// color: #B5B5B5;
		}

		.u-form-item--right {
			font-size: 32rpx;
			height: 70rpx;
			line-height: 70rpx;
			border: 1px solid #E3E3E3;
			box-shadow: 9rpx 9rpx 9rpx rgba($color: #000000, $alpha: .06);
			padding: 0 20rpx;
			border-radius: 40rpx;
			color: $text-color;

			.u-input {
				justify-content: center;
				align-items: center;
			}

			.u-input__input {
				height: 50rpx !important;
				min-height: 50rpx !important;
			}
		}
	}
</style>